package com.service.story;

import com.domain.HttpResponse;
import com.domain.ex.BizException;
import com.domain.ex.Codes;
import com.domain.myenum.ContentEnum;
import com.domain.myenum.RoleEnum;
import com.dto.BulletinDto;
import com.dto.StoryExtDto;
import com.dto.UserExtDto;
import com.event.story.StoryEvent;
import com.event.story.StoryEventListener;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.eventbus.EventBus;
import com.mapper.generator.ShStoryMapper;
import com.mapper.generator.ShTagMapper;
import com.mapper.self.CompanyMapper;
import com.mapper.self.StoryMapper;
import com.mapper.self.TagMapper;
import com.pojo.ShCompany;
import com.pojo.ShStory;
import com.pojo.ShTag;
import com.service.user.UserService;
import com.utils.DateUtils;
import com.utils.RandomUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by Huoyunren on 2016-07-01.
 */
@Service
public class StoryServiceImpl implements StoryService {

  @Autowired
  private StoryMapper storyMapper;
  @Autowired
  private ShStoryMapper shStoryMapper;
  @Autowired
  private ShTagMapper shTagMapper;
  @Autowired
  private TagMapper tagMapper;
  @Autowired
  private StoryEventListener storyEventListener;
  @Autowired
  private CompanyMapper companyMapper;

  @Override
  public List<StoryExtDto> list(Integer pageNo, Integer pageSize, String email, String orderField, Integer storyType,Integer tag) {
    if (pageNo > 0) {
      pageNo -= 1;
    }
    if (storyType == null) {
      storyType = ContentEnum.Content.getCode();
    }
    List<ShTag> tagList = tagMapper.list();
    Map<Integer,ShTag> tagMap = Maps.newHashMap();
    for (ShTag shTag : tagList) {
      tagMap.put(shTag.getId(), shTag);
    }
    List<StoryExtDto> list = storyMapper.list(pageNo * pageSize, pageSize, email, orderField, storyType,tag);
    for (StoryExtDto dto : list) {
      if (tagMap.containsKey(Integer.valueOf(dto.getTag()))){
        dto.setTag(tagMap.get(Integer.valueOf(dto.getTag())).getName());
      }else{
        dto.setTag("未分类");
      }
      dto.setContent(dto.getContent().replace("@#@", "<br>"));
    }
    return list;
  }

  @Override
  public List<BulletinDto> bulletin(Integer pageNo, Integer pageSize, String email, String orderField, Integer storyType) {
    List<BulletinDto> bulletinDtos = Lists.newArrayList();
    if (pageNo > 0) {
      pageNo -= 1;
    }
    List<StoryExtDto> list = storyMapper.list(pageNo * pageSize, pageSize, email, orderField, storyType,null);
    if (CollectionUtils.isEmpty(list)) {
      return bulletinDtos;
    }
    Map<String, List> map = Maps.newHashMap();
    String date = "";
    for (StoryExtDto dto : list) {
      if (DateUtils.isToday(dto.getCreateTime())) {
        date = "今天";
      } else {
        date = dto.getCreateTime().substring(0, dto.getCreateTime().indexOf(" "));
      }
      if (!map.containsKey(date)) {
        map.put(date, Lists.newArrayList());
      }
      map.get(date).add(dto);
    }
    for (String s : map.keySet()) {
      BulletinDto bulletinDto = new BulletinDto();
      bulletinDto.setDate(s);
      bulletinDto.setList(map.get(s));
      bulletinDtos.add(bulletinDto);
    }
    Collections.sort(bulletinDtos, new Comparator<BulletinDto>() {
      @Override
      public int compare(BulletinDto o1, BulletinDto o2) {
        return o2.getDate().compareTo(o1.getDate());
      }
    });
    return bulletinDtos;
  }

  @Override
  public Object save(String email, String title, String subTitle, String content, String img, Integer storyType, Integer chooseTag) {
    ShStory story = buildDefaultStory(email, title, subTitle, content, img, storyType, chooseTag);
    story.setDataVersion(1);
    shStoryMapper.insertSelective(story);
    // - 新文章通知粉丝
    storyNotify(email,title,subTitle,story.getUuid());

    return HttpResponse.create(Codes.OK, "", story);
  }

  // - 新文章通知
  private void storyNotify(String email, String title, String subTitle, String uuid) {
    EventBus eventBus = new EventBus(StoryEvent.class.getName());
    StoryEvent storyEvent = new StoryEvent(email,title,subTitle,uuid);
    eventBus.register(storyEventListener);
    eventBus.post(storyEvent);
  }

  private ShStory buildDefaultStory(String email, String title, String subTitle, String content, String img, Integer storyType, Integer chooseTag) {
    ShStory story = new ShStory();
    story.setEmail(email);
    story.setTitle(title);
    story.setSubTitle(subTitle);
    story.setContent(content);
    story.setImgUrl(img);
    story.setReadCount(0);
    story.setUuid(RandomUtils.getUuid());
    story.setCreateTime(DateUtils.currentDate());
    story.setStoryType(storyType);
    if (chooseTag!=null){
      story.setTag(chooseTag.toString());
    }
    return story;
  }

  @Override
  public StoryExtDto queryByUuid(String uuid) {
    StoryExtDto story = new StoryExtDto();
    story = storyMapper.queryByUuid(uuid);
    if (story == null) {
      story = new StoryExtDto();
    }
    dealOldData(story);
    story.setCreateTime(story.getCreateTime().substring(0, story.getCreateTime().length() - 2));
    ShTag tag = shTagMapper.selectByPrimaryKey(Integer.valueOf(story.getTag()));
    if (tag != null){
      story.setTag(tag.getName());
    }else{
      story.setTag("未分类");
    }
    return story;
  }

  private void dealOldData(StoryExtDto story) {
    if (story.getDataVersion() == 1){
      return;
    }
    if (StringUtils.isNotBlank(story.getContent())) {
      String content = story.getContent();
      content = content.replace("@#@", "<br>");
      // - 反解析
      content = content.replace("&lt;", "<");
      content = content.replace("&gt;", ">");
      story.setContent(content);
    }
  }

  @Override
  public void incrReadCount(String uuid) {
    storyMapper.incrReadCount(uuid);
  }

  @Override
  public void del(int storyId,String authEmail) {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    Object obj = request.getSession().getAttribute("email");
    if (obj == null){
      throw BizException.create(Codes.NotLogin);
    }
    ShStory story = shStoryMapper.selectByPrimaryKey(storyId);
    if (story == null){
      return;
    }
    if (obj.toString().equals(authEmail)){
      // - 自己删除
      shStoryMapper.deleteByPrimaryKey(storyId);
    }else {
      // - 管理员删除
      ShCompany company = companyMapper.queryByEmail(obj.toString());
      if (!RoleEnum.SuperAdmin.getCode().toString().equals(company.getRole()) && !RoleEnum.Admin.getCode().toString().equals(company.getRole())){
        // - 非管理员没有权限删除别人的数据
        throw BizException.create(Codes.AuthError);
      }
      shStoryMapper.deleteByPrimaryKey(storyId);
    }
  }
}
